#include "../logs/whlog.h"
#include <vector>
#include <thread>
#include <chrono>

void bench(const std::string &logger_name, size_t thr_count, size_t msg_count, size_t msg_len)
{   
    // 1.获取日志器
    whlog::Logger::ptr logger = whlog::getLogger(logger_name);
    if(logger.get() == nullptr)
    {
        return;
    }
    std::cout << "测试日志：" << msg_count << "条，总大小：" << (msg_count * msg_len) / 1024 << "KB\n"; 
    // 2.组织指定长度的日志消息
    std::string msg(msg_len - 1, 'A');
    // 3.创建指定数量的线程
    std::vector<std::thread> threads;
    std::vector<double> cost_arry(thr_count);
    size_t msg_per_thr = msg_count / thr_count;
    for(int i = 0; i < thr_count; i++)
    {
        threads.emplace_back([&, i](){
            // 4.线程内部开始进行计时
            auto start = std::chrono::high_resolution_clock::now();
            // 5.开始循环写日志
            for(int j = 0; j < msg_per_thr; j++)
            {
                logger->fatal("%s",msg);
            }
            // 6.写完后结束计时
            auto end = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost = end - start;
            cost_arry[i] = cost.count();
            std::cout << "线程" << i << "：" << "\t输出数量：" << msg_per_thr << "，耗时：" << cost.count() << "s\n";
        });
    }
    for(int i = 0; i < thr_count; i++)
    {
        threads[i].join();
    }

    // 7.计算总耗时，因为线程并行运行，所以是耗时最长的那个
    double max_cost = cost_arry[0];
    for(int i = 0; i < thr_count; i++) max_cost = max_cost < cost_arry[i] ? cost_arry[i] : max_cost;
    size_t msg_per_sec = msg_count / max_cost;
    size_t size_per_sec = (msg_count * msg_len) / (max_cost * 1024);
    // 8.进行输出打印
    std::cout << "每秒输出日志数量：" << msg_per_sec << "条\n";
    std::cout << "每秒输出日志大小：" << size_per_sec << "条\n";
}

void sync_bench()
{
    // 同步日志器简单测试
    std::unique_ptr<whlog::LoggerBuilder> builder(new whlog::GlobalLoggerBuilder());
    builder->buildLoggerName("sync_logger");
    builder->buildLogformatter("%m%n");
    builder->buildLoggerType(whlog::LoggerType::LOGGER_SYNC);
    builder->buildLogSink<whlog::FileSink>("./logfile/sync.log");
    builder->build();
    bench("sync_logger", 3, 1000000, 100);
}
void async_bench()
{
    // 异步日志器简单测试
    std::unique_ptr<whlog::LoggerBuilder> builder(new whlog::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLogformatter("%m%n");
    builder->buildLoggerType(whlog::LoggerType::LOGGER_ASYNC);
    builder->buildEnableUnSalfAsync();
    builder->buildLogSink<whlog::FileSink>("./logfile/async.log");
    builder->build();
    bench("async_logger", 3, 1000000, 100);
}

int main()
{
    async_bench();
    return 0;
}